package com.flida.ecfront.control;

import com.alibaba.fastjson.JSONObject;
import com.flida.bana.common.util.DozerMapperManager;
import com.flida.bana.common.util.JwtUtil;
import com.flida.bana.common.util.MD5Util;
import com.flida.bana.common.util.ResponseUtil;
import com.flida.echart.basic.api.account.entity.User;
import com.flida.echart.basic.api.account.entity.UserDto;
import com.flida.echart.basic.api.account.service.GateUserService;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;


/**
 * Created by yzc on 2016/12/4.
 */
@Controller
@RequestMapping("/user")
public class UserControl {
    private static final Logger logger = LogManager.getLogger(UserControl.class);

    @Resource
    private GateUserService gateUserService;
    //	@Value("${spring.profiles.auth}")
//	private String auth;
    @Autowired
    public  JwtUtil jwt;
    @Autowired
    public DozerMapperManager dozerMapperManager;
    @RequestMapping(value = "login.html", method = {RequestMethod.GET,
            RequestMethod.POST}, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public ResponseEntity<String> login(
            @RequestParam(value = "username", required = true) String username,
            @RequestParam(value = "password", required = true) String password) {
        try {

            //System.out.println("password:auth"+auth+"|" + MD5Util.md5(password + auth));
            User user = gateUserService.selectByUserNameAndPass(username, MD5Util.md5(password));
            UserDto userDto = null;
            JSONObject jo = null;
            if (null != user) {
                userDto = new UserDto();
                dozerMapperManager.map(user, userDto);
                String token = jwt.generalToken(user);
                String refreshToken = jwt.generalRefreshToken(user);
                // 把token 放入redis,用redis来控制生命周期，用redis控制刷新
                jo = new JSONObject();
                jo.put("token", token);
                jo.put("refreshToken", refreshToken);
                jo.put("data", userDto);
            } else {
                return ResponseUtil.exception("账号或者密码错误");
            }
            return ResponseUtil.success(jo);
        } catch (Exception e) {
            logger.error(e);
            return ResponseUtil.unKonwException();
        }
    }
}
